package org.poem.incrementhandle;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.poem.CanalClientEntryVO;
import org.poem.CanalClientHeadEntityVO;
import org.poem.StringUtils;
import org.poem.exec.annotation.CanalHandle;
import org.poem.handler.increment.AbstractClientIncrementHandler;
import org.poem.enums.EnumDataType;
import org.poem.sql.SqlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * mysql数据库的处理方式
 *
 * @author poem
 */
@Service
@CanalHandle
public class MysqlCanalIncrementHandler extends AbstractClientIncrementHandler {


    private static final Logger logger = LoggerFactory.getLogger(MysqlCanalIncrementHandler.class);

    @Autowired
    @Qualifier("mysqlJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取key的数据列
     *
     * @param canalClientHeadEntityVO
     * @return
     */
    private CanalClientEntryVO getKey(CanalClientHeadEntityVO canalClientHeadEntityVO) throws Exception {
        if (canalClientHeadEntityVO.getBeforeEntries() != null){
            for (CanalClientEntryVO entry : canalClientHeadEntityVO.getBeforeEntries()) {
                if (entry.getKey()) {
                    return entry;
                }
            }
        }

        return null;
    }

    /**
     * 删除数据
     *
     * @param canalClientHeadEntityVO
     */
    @Override
    protected void delete(CanalClientHeadEntityVO canalClientHeadEntityVO) throws Exception {
        CanalClientEntryVO entry = getKey(canalClientHeadEntityVO);
        EnumDataType enumDataType = EnumDataType.MYSQL;
        String sql = "";
        if (entry != null) {
            sql = SqlUtils.createDeleteSqlByKeyColumn(entry, canalClientHeadEntityVO, enumDataType);
        } else {
            sql = SqlUtils.createDeleteSqlColumn(canalClientHeadEntityVO, enumDataType);
        }
        logger.info("delete");
        jdbcTemplate.execute(String.join(";\n", sql));

    }


    /**
     * 更新数据
     *
     * @param canalClientHeadEntityVO
     */
    @Override
    protected void update(CanalClientHeadEntityVO canalClientHeadEntityVO) throws Exception {
        CanalClientEntryVO entry = getKey(canalClientHeadEntityVO);
        EnumDataType enumDataType = EnumDataType.MYSQL;
        String sql = "";
        if (entry != null) {
            sql = SqlUtils.createUpdateSqlByKeyColumn(entry, canalClientHeadEntityVO, enumDataType);
        } else {
            sql = SqlUtils.createUpdateSqlColumn(canalClientHeadEntityVO, enumDataType);
        }
        logger.info("update");
        jdbcTemplate.execute(String.join(";\n", sql));
    }

    /**
     * 插入数据
     *
     * @param canalClientHeadEntityVO
     */
    @Override
    protected void insert(CanalClientHeadEntityVO canalClientHeadEntityVO) throws Exception {
        List<Map<String, Object>> metadata = Lists.newArrayList();
        List<String> columns = Lists.newArrayList();
        Map<String, String> typeZip = Maps.newHashMap();
        EnumDataType enumDataType = EnumDataType.MYSQL;
        Map<String, Object> result = Maps.newHashMap();
        if (canalClientHeadEntityVO.getEntries()  != null) {
            for (CanalClientEntryVO beforeEntry : canalClientHeadEntityVO.getEntries()) {
                columns.add(beforeEntry.getName());
                typeZip.put(beforeEntry.getName(), beforeEntry.getMysqlType());
                result.put(beforeEntry.getName(), beforeEntry.getValue());
            }
        }
        metadata.add(result);
        List<String> insertSql = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(canalClientHeadEntityVO.getSql())){
            insertSql = canalClientHeadEntityVO.getSql();
        }else{
           insertSql = SqlUtils.createInsertSql(canalClientHeadEntityVO.getTableName(), metadata, columns, typeZip, enumDataType);
        }
        logger.info("insert");
        for (String s : insertSql) {
            if (StringUtils.isNoneEmpty(s) && StringUtils.isNoneEmpty(s.trim())) {
                jdbcTemplate.execute(s);
            }
        }

    }


    /**
     * 新增表
     * mysql to postgres
     *
     * @param canalClientHeadEntityVO
     */
    @Override
    protected void createTable(CanalClientHeadEntityVO canalClientHeadEntityVO) throws Exception {
        logger.info("createTable");
        //mysql的可以直接执行
        jdbcTemplate.execute(String.join(";\n", canalClientHeadEntityVO.getSql()));
    }

    /**
     * 删除表
     */
    @Override
    protected void deleteTable(CanalClientHeadEntityVO canalClientHeadEntityVO) throws Exception {
        logger.info("deleteTable");
        //mysql的可以直接执行
        jdbcTemplate.execute(String.join(";\n", canalClientHeadEntityVO.getSql()));
    }
}
